import * as SparkMD5 from "spark-md5";
import { splitFilename } from "./fs";

export function md5FromBuffer(buffer: Buffer) {
	const key = SparkMD5.hash(buffer.toString());
	return key;
}

export function md5FromBuffer2(buffer: Buffer) {
	let start = 0;
	let uploadTimes = 0;
	const chunkSize = 1024 * 1024;
	const spark = new SparkMD5.ArrayBuffer();

	while (start <= buffer.length) {
		start = uploadTimes * chunkSize;
		const chunk = buffer.slice(start, start + chunkSize);
		spark.append(bufToArrayBuffer(chunk));
		uploadTimes++;
	}

	const endKey = spark.end();

	return endKey;
}

/**
 *
 * @param buf 待修改的 Buffer 对象
 * @returns Buffer转ArrayBuffer
 */
export function bufToArrayBuffer(buf: Buffer): ArrayBuffer {
	const ab = new ArrayBuffer(buf.length);
	const view = new Uint8Array(ab);

	for (let i = 0; i < buf.length; ++i) {
		view[i] = buf[i];
	}
	return ab;
}

function getChunkIndex(file: string) {
	const id = file.split("chunk-")[1];
	if (typeof id !== "string") {
		return Number(file);
	}

	const { name } = splitFilename(id);
	return Number(name);
}

export function chunkSort(a: string, b: string) {
	return getChunkIndex(a) - getChunkIndex(b);
}
